package mail

import (
	"github.com/gogf/gf/container/gmap"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	gomail "gopkg.in/gomail.v2"
	"strings"
)

type Mail struct {
	mail        *gomail.Dialer
	config      map[string]string
}

var (
	instances   = gmap.NewStrAnyMap(true)
	DefaultName = "default"
)

func Instance(name ...string) *Mail {
	key := DefaultName
	if len(name) > 0 && name[0] != "" {
		key = "mail.config." + name[0]
	} else {
		key = "mail.config." + key
	}
	return instances.GetOrSetFuncLock(key, func() interface{} {
		return New(key)
	}).(*Mail)
}

func New(name string) *Mail {
	config := g.Cfg().GetMapStrStr(name)
	if config == nil {
		panic("发送失败：邮件发送配置文件有误")
	}

	m := &Mail{}
	m.config = config
	m.mail = gomail.NewDialer(config["host"], gconv.Int(config["port"]), config["addr"], config["pass"])
	return m
}

// 客户端示例
func Client(name ...string) *Mail {
	return Instance(name...)
}

// 发送邮件
func (m *Mail) SendMail(form, mailTo, subject, content string) error {

	if subject == "" {
		subject = "无主题"
	}
	//设置字符集
	s := gomail.NewMessage(gomail.SetCharset(m.config["charset"]))
	//设置发件人
	s.SetHeader("From", m.config["addr"])
	//设置发送给多个用户
	mailArrTo := strings.Split(mailTo, ",")
	s.SetHeader("To", mailArrTo...)
	//设置邮件主题
	s.SetHeader("Subject", subject)
	//设置邮件正文
	s.SetBody(m.config["content_type"], content)
	// 发送邮件
	err := m.mail.DialAndSend(s)
	if err != nil {
		return err
	}
	return nil
}
